declare const os: any;
const isAndroid = (/android/gi).test(navigator.appVersion);
/**
 *  数据储存
 */
export default class LocalStorage<KEYS> {
    /**
     * 设置缓存
     * @param key 
     * @param val 
     * @param expire  过期时间 单位毫秒，如10秒后后期则是：10000，0表示永不过期
     */
    public set<K extends keyof KEYS>(key: K, val: KEYS[K], expire: number = 0) {
        const model = JSON.stringify({
            value: val,
            expire: expire > 0 ? Date.now() + expire : expire
        });
        this.getStorage().setItem(key, model);
        return this;

    }
    /**
     * 
     * @param key 
     * @param def 当缓存不存在时或者过期时 默认值
     */
    public get<K extends keyof KEYS>(key: K, def?: KEYS[K]): KEYS[K] | null {
        const value: string | null = this.getStorage().getItem(key);
        if (!value) {
            return this.parseDefault(def);
        }
        try {
            const model = JSON.parse(value);
            if (model.expire === 0 || model.expire > Date.now()) {
                return model.value;
            }
            return this.parseDefault(def);
        } catch (error) {
            return this.parseDefault(def);
        }

    }

    public remove<K extends keyof KEYS>(key: K) {
        this.getStorage().removeItem(key);
        return this;
    }

    private getStorage() {
        if (isAndroid && typeof os !== 'undefined') {
            return os.localStorage();
        }
        return window.localStorage;
    }

    private parseDefault(def: any) {
        if (typeof def !== 'undefined') {
            return def;
        }
        return null;
    }


}
